import cgi
import datetime
import urllib
import webapp2
import jinja2
import os

# GAE framework specific packages
from webapp2_extras import sessions
from google.appengine.ext import db
from google.appengine.api import users


#############################
#
# Model Classes
#
#############################

class Agent(db.Model):
  """Models an individual real estate agent."""
  created_by = db.UserProperty()
  created_on = db.DateTimeProperty(auto_now_add=True)
  last_name = db.StringProperty()
  first_name = db.StringProperty()
  mobile = db.PhoneNumberProperty()
  email = db.EmailProperty()
  address = db.PostalAddressProperty()

class Listing(db.Model):
  """Models an individual real estate listing."""
  author = db.UserProperty()
  header = db.StringProperty()
  mls_number = db.StringProperty()
  price = db.StringProperty()
  address1 = db.StringProperty()
  city = db.StringProperty()
  state = db.StringProperty()
  zip = db.StringProperty()
  square_footage = db.StringProperty()
  bedrooms = db.StringProperty()
  bathrooms = db.StringProperty()
  garage = db.StringProperty()
  county = db.StringProperty()
  schools = db.StringProperty()
  acreage = db.StringProperty()
  overview = db.StringProperty(multiline=True)
  
  date_created = db.DateTimeProperty(auto_now_add=True)

#############################
#
# Utility Functions
#
#############################

def brokerage_key(brokerage_name):
  """Constructs a datastore key with brokerage_name."""
  return db.Key.from_path('Brokerage', brokerage_name)

#############################
#
# Request Handlers
#
#############################

class BaseHandler(webapp2.RequestHandler):
  def render_template(self, template, template_values={}):
    template = jinja_environment.get_template(template)
    self.response.out.write(template.render(template_values))
    
  def inflate_from_request(self, m):
    """ sets all the parameters from the request into model 'm' provided
    the request parameter name matches that of the model's class 
    member's name """
    for k in m.__class__.__dict__.keys():
      if k.startswith('_') or len(self.request.get(k)) == 0:
        continue
      #print k, type(getattr(m.__class__, k)), len(self.request.get(k))
      setattr(m, k, self.request.get(k))

class MainPage(BaseHandler):
  def get(self):
    listings_query = Listing.all().ancestor(
      brokerage_key(brokerage_name)).order('-date_created')
    listings = listings_query.fetch(10)

    template_values = {
      'listings': listings,
    }
    self.render_template('templates/index.html', template_values)

class NewListingHandler(BaseHandler):
  def get(self):
    self.render_template('templates/new_listing.html')

  def post(self):
    # We set the same parent key on the 'Listing' to ensure each listing is in
    # the same brokerage. Queries across the single brokerage will be
    # consistent. However, the write rate to a single brokerage should
    # be limited to ~1/second.
    listing = Listing(parent=brokerage_key(brokerage_name))

    if users.get_current_user():
      listing.author = users.get_current_user()

    self.inflate_from_request(listing)

    listing.put()
    self.redirect('/?' + urllib.urlencode({'brokerage_name': brokerage_name}))

#############################
#
# Modual-level code
#
#############################

# brokerage_name is a good place to start multitenant features but
# is NOT a namespace.
brokerage_name = "Scott-Ogle"

# setup the templating environment
jinja_environment = jinja2.Environment(
  loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

# setup the webapp environment
app = webapp2.WSGIApplication([('/', MainPage),
                               ('/newlisting', NewListingHandler)],
                              debug=True)